<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gemini AI 助手</title>

    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 16px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #4f46e5, #7c3aed);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
        }

        .header p {
            opacity: 0.9;
            font-size: 1.1rem;
        }

        .form-container {
            padding: 40px;
        }

        .form-group {
            margin-bottom: 25px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #374151;
        }

        input[type="url"],
        input[type="text"],
        select,
        textarea {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e5e7eb;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s ease;
        }

        input[type="url"]:focus,
        input[type="text"]:focus,
        select:focus,
        textarea:focus {
            outline: none;
            border-color: #4f46e5;
            box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
        }

        textarea {
            resize: vertical;
            min-height: 100px;
            padding-right: 80px;
            
        }

        .submit-btn {
            width: 100%;
            background: linear-gradient(135deg, #4f46e5, #7c3aed);
            color: white;
            border: none;
            padding: 16px;
            border-radius: 8px;
            font-size: 18px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s ease, box-shadow 0.2s ease;
        }

        .submit-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(79, 70, 229, 0.3);
        }

        .submit-btn:disabled {
            background: #9ca3af;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }

        .spinner {
            border: 4px solid #f3f4f6;
            border-top: 4px solid #4f46e5;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }
        
        /* 彩虹文字动画 */
        .rainbow-model-name {
            font-size: 14px;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .rainbow-text {
            font-weight: 600;
            background-image: linear-gradient(
                90deg,
                #ff0000, #ff9a00, #d0de21, #4fdc4a, #3fdad8, #2fc9e2, #1c7fee, #5f15f2, #ba0cf8, #fb07d9, #ff0000
            );
            background-size: 200% auto;
            color: transparent;
            -webkit-background-clip: text;
            background-clip: text;
            animation: rainbow-animation 5s linear infinite;
            display: inline-block;
            text-shadow: 0 0 10px rgba(255, 255, 255, 0.2);
        }
        
        @keyframes rainbow-animation {
            to {
                background-position: 200% center;
            }
        }
        
        /* 图片选择交互优化 */
        .images-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
            gap: 15px;
            margin-top: 15px;
        }
        
        .image-item {
            position: relative;
            cursor: grab;
            transition: all 0.2s ease;
            border-radius: 8px;
            overflow: hidden;
        }
        
        .image-item:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        
        .image-item.dragging {
            opacity: 0.7;
            box-shadow: 0 10px 20px rgba(0,0,0,0.2);
            cursor: grabbing;
        }
        
        .image-preview-wrapper {
            position: relative;
            aspect-ratio: 1 / 1;
            border-radius: 8px;
            overflow: hidden;
            background: #f3f4f6;
            pointer-events: none; /* 允许拖拽事件穿透 */
        }
        
        .preview-thumbnail {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.3s ease;
            pointer-events: none; /* 允许拖拽事件穿透 */
        }
        
        .image-item:hover .preview-thumbnail {
            transform: scale(1.05);
        }
        
        .image-number {
            position: absolute;
            top: 8px;
            left: 8px;
            width: 24px;
            height: 24px;
            background: rgba(0, 0, 0, 0.5);
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            font-weight: bold;
            z-index: 2;
        }
        
        .remove-image-btn {
            position: absolute;
            top: 8px;
            right: 8px;
            width: 24px;
            height: 24px;
            border: none;
            background: rgba(239, 68, 68, 0.9);
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            cursor: pointer;
            z-index: 2;
            opacity: 0;
            transition: opacity 0.2s ease;
            pointer-events: auto; /* 删除按钮需要响应点击 */
        }
        
        .image-item:hover .remove-image-btn {
            opacity: 1;
        }
        
        .image-info-overlay {
            padding: 8px;
            background: #f9fafb;
            display: flex;
            align-items: center;
            gap: 5px;
            border-top: 1px solid #e5e7eb;
            pointer-events: none; /* 允许拖拽事件穿透 */
        }
        
        .type-icon {
            font-size: 12px;
        }
        
        .image-short-info {
            font-size: 12px;
            color: #6b7280;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .image-counter {
            color: #4b5563;
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 10px;
        }
        
        .drag-hint {
            color: #6b7280;
            font-size: 12px;
            margin-bottom: 10px;
            background: #f3f4f6;
            padding: 6px 10px;
            border-radius: 4px;
            display: inline-block;
        }
        
        /* 整个页面拖拽效果 */
        .dragover-body {
            position: relative;
        }
        
        .dragover-body::before {
            content: '📁 拖拽图片文件到此处上传';
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(59, 130, 246, 0.1);
            backdrop-filter: blur(2px);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            font-weight: bold;
            color: #2563eb;
            z-index: 9999;
            border: 3px dashed #2563eb;
            box-sizing: border-box;
        }
        
        .floating-success {
            position: fixed;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(16, 185, 129, 0.9);
            color: white;
            padding: 10px 20px;
            border-radius: 8px;
            font-size: 14px;
            z-index: 1000;
            animation: fadeInOut 2s ease forwards;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        
        @keyframes fadeInOut {
            0% { opacity: 0; transform: translate(-50%, 20px); }
            15% { opacity: 1; transform: translate(-50%, 0); }
            85% { opacity: 1; transform: translate(-50%, 0); }
            100% { opacity: 0; transform: translate(-50%, -20px); }
        }
        
        .upload-area.minimized {
            padding: 10px;
            transition: all 0.3s ease;
        }
        
        .upload-area.minimized p {
            display: none;
        }
        
        .upload-area {
            transition: all 0.3s ease;
        }

        .result {
            display: none;
            margin-top: 30px;
            padding: 20px;
            background: #f9fafb;
            border-radius: 8px;
        }

        .result h3 {
            margin-bottom: 15px;
            color: #374151;
        }

        .image-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
        }

        .result-image {
            width: 100%;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        .result-image-container {
            position: relative;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .result-image-buttons {
            display: flex;
            gap: 8px;
            margin-top: 10px;
            opacity: 1;
        }

        .reuse-btn,
        .download-btn {
            padding: 6px 12px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 12px;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .reuse-btn {
            background: #4f46e5;
            color: white;
        }

        .reuse-btn:hover {
            background: #4338ca;
            transform: translateY(-1px);
        }

        .download-btn {
            background: #059669;
            color: white;
        }

        .download-btn:hover {
            background: #047857;
            transform: translateY(-1px);
        }

        .error {
            display: none;
            background: #fef2f2;
            border: 1px solid #fecaca;
            color: #dc2626;
            padding: 15px;
            border-radius: 8px;
            margin-top: 20px;
        }

        .image-input-section {
            border: 2px dashed #d1d5db;
            border-radius: 12px;
            padding: 20px;
            text-align: center;
            transition: border-color 0.3s ease;
            margin-bottom: 25px;
        }

        .image-input-section.dragover {
            border-color: #4f46e5;
            background-color: #f8fafc;
        }

        .image-input-section.paste-ready {
            border-color: #059669;
            background-color: #f0fdf4;
            animation: pulse 2s infinite;
        }

        @keyframes pulse {

            0%,
            100% {
                opacity: 1;
            }

            50% {
                opacity: 0.8;
            }
        }

        .upload-area {
            margin-bottom: 15px;
        }

        .upload-btn {
            background: #4f46e5;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            margin-right: 10px;
            transition: background-color 0.3s ease;
        }

        .upload-btn:hover {
            background: #4338ca;
        }

        .file-input {
            display: none;
        }

        .url-input-container {
            display: flex;
            gap: 10px;
            align-items: center;
            margin-top: 15px;
        }

        .url-input {
            flex: 1;
        }

        .preview-btn {
            background: #059669;
            color: white;
            border: none;
            padding: 12px 20px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            white-space: nowrap;
        }

        .preview-btn:hover {
            background: #047857;
        }

        .image-preview {
            display: none;
            margin-top: 20px;
            text-align: center;
        }

        .preview-image {
            max-width: 100%;
            max-height: 300px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        .preview-info {
            margin-top: 10px;
            color: #6b7280;
            font-size: 14px;
        }

        .clear-image {
            background: #dc2626;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 12px;
            margin-top: 10px;
        }

        .clear-image:hover {
            background: #b91c1c;
        }



        .row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        .prompt-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 25px;
        }

        .prompt-left,
        .prompt-right {
            margin-bottom: 0;
        }

        @media (max-width: 768px) {
            .row {
                grid-template-columns: 1fr;
            }

            .prompt-row {
                grid-template-columns: 1fr;
                gap: 15px;
            }

            .header h1 {
                font-size: 2rem;
            }

            .form-container {
                padding: 20px;
            }

            .url-input-container {
                flex-direction: column;
            }

            .preview-btn {
                width: 100%;
            }





            textarea {
                padding-right: 16px;
                /* 移动端恢复正常内边距 */
            }
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="header">
            <h1>🤖 Gemini AI 助手</h1>
            <p>使用 Gemini AI 技术编辑图片或生成内容</p>
        </div>

        <div class="form-container">
            <form id="imageEditForm">
                <div class="form-group">
                    <label>选择图片 (支持多张，可选)</label>
                    <div class="image-input-section" id="imageInputSection">
                        <div class="upload-area">
                            <p style="margin-bottom: 15px; color: #6b7280;">
                                拖拽图片到此处、点击上传或按 Ctrl+V 粘贴剪贴板图片
                            </p>
                            <div style="display: flex; gap: 10px; justify-content: center; flex-wrap: wrap;">
                                <button type="button" class="upload-btn"
                                    onclick="document.getElementById('fileInput').click()">
                                    📁 选择文件
                                </button>
                                <button type="button" class="upload-btn" onclick="pasteFromClipboard()">
                                    📋 粘贴图片
                                </button>
                            </div>
                            <input type="file" id="fileInput" class="file-input" accept="image/*" multiple>
                        </div>

                        <div style="margin: 15px 0; color: #9ca3af;">或者</div>

                        <div class="url-input-container">
                            <input type="url" id="imageUrl" class="url-input"
                                placeholder="输入图片 URL: https://example.com/image.jpg">
                            <button type="button" class="preview-btn" id="addUrlBtn">➕ 添加</button>
                        </div>
                    </div>

                    <div class="image-preview" id="imagePreview">
                        <img id="previewImage" class="preview-image" alt="图片预览">
                        <div class="preview-info" id="previewInfo"></div>
                        <button type="button" class="clear-image" id="clearImage">清除图片</button>
                    </div>
                </div>

                <div class="form-group">
                    <label for="prompt">提示词 *</label>
                    <textarea id="prompt" name="prompt" required
                        placeholder="描述你想要对图片进行的编辑，例如：将背景改为蓝天白云，或者 Change the background to blue sky with white clouds"></textarea>
                </div>

                <div class="row">
                    <div class="form-group">
                        <div class="rainbow-model-name">
                            <strong>模型:</strong> <span class="rainbow-text">Gemini 2.5 Flash Image Preview</span>
                        </div>
                        <input type="hidden" name="modelType" value="gemini" />
                    </div>


                </div>

                <button type="submit" class="submit-btn" id="submitBtn">
                    开始处理
                </button>
            </form>

            <div class="loading" id="loading">
                <div class="spinner"></div>
                <p>正在处理中，请稍候...</p>
            </div>

            <div class="error" id="error"></div>

            <div class="result" id="result">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                    <h3 style="margin: 0;">处理结果</h3>
                    <button type="button" class="clear-image" id="clearResultBtn" style="display: none;">🗑️ 清除结果</button>
                </div>
                <div class="image-grid" id="imageGrid"></div>
            </div>
        </div>
    </div>

    <script>
        // const API_KEY = 'sk-7vylVCM3AHsxeIOeCb11BfB235314eD1B0D9Fe21F888B1De';
        const API_KEY = 'sk-NNISovW1HS5UJbyRA36e5fF05aA9460a957dD8799725E96f';
        const BASE_URL = 'https://api.laozhang.ai/v1';

        let currentImages = [];
        let uploadedFiles = [];

        // 初始化事件监听器
        document.addEventListener('DOMContentLoaded', function () {
            initializeEventListeners();
        });

        function initializeEventListeners() {
            // 文件上传
            document.getElementById('fileInput').addEventListener('change', handleFileUpload);

            // URL 预览
            document.getElementById('addUrlBtn').addEventListener('click', handleUrlPreview);

            // 清除图片
            document.getElementById('clearImage').addEventListener('click', clearImage);

            // 清除结果
            document.getElementById('clearResultBtn').addEventListener('click', clearResult);



            // 拖拽上传 - 支持整个页面拖拽
            document.body.addEventListener('dragover', handleDragOver);
            document.body.addEventListener('dragleave', handleDragLeave);
            document.body.addEventListener('drop', handleDrop);

            // 剪贴板粘贴支持
            document.addEventListener('paste', handlePaste);
            document.addEventListener('keydown', handleKeyDown);

            // 表单提交
            document.getElementById('imageEditForm').addEventListener('submit', handleFormSubmit);
        }

        async function handleFileUpload(e) {
            const files = e.target.files;
            for (let i = 0; i < files.length; i++) {
                const file = files[i];
                if (file) {
                    await addImageFile(file);
                }
            }
        }

        async function addImageFile(file) {
            if (!file.type.startsWith('image/')) {
                showError('请选择有效的图片文件');
                return;
            }

            if (file.size > 10 * 1024 * 1024) { // 10MB
                showError(`文件 ${file.name} 大小不能超过 10MB`);
                return;
            }

            const reader = new FileReader();
            reader.onload = function (e) {
                const imageData = {
                    url: e.target.result,
                    file: file,
                    info: `文件: ${file.name} (${formatFileSize(file.size)})`,
                    type: 'file'
                };
                currentImages.push(imageData);
                uploadedFiles.push(file);
                updateImagesPreview();
            };
            reader.readAsDataURL(file);
        }

        function updateImagesPreview() {
            const imagesList = document.getElementById('imagesList');
            const clearAllBtn = document.getElementById('clearAllBtn');
            
            if (!imagesList) {
                // 如果还没有这个元素，先创建
                createImagesPreviewElements();
                return updateImagesPreview();
            }

            imagesList.innerHTML = '';
            
            if (currentImages.length === 0) {
                clearAllBtn.style.display = 'none';
                document.getElementById('imagePreview').style.display = 'none';
                
                // 显示上传提示
                document.getElementById('imageInputSection').classList.remove('has-images');
                document.querySelector('.upload-area').classList.remove('minimized');
                return;
            }

            clearAllBtn.style.display = 'block';
            document.getElementById('imagePreview').style.display = 'block';
            
            // 添加图片后缩小上传区域
            document.getElementById('imageInputSection').classList.add('has-images');
            document.querySelector('.upload-area').classList.add('minimized');

            // 添加计数器
            const imageCounter = document.createElement('div');
            imageCounter.className = 'image-counter';
            imageCounter.textContent = `已选择 ${currentImages.length} 张图片`;
            imagesList.appendChild(imageCounter);
            
            // 添加拖拽排序提示
            if (currentImages.length > 1) {
                const dragHint = document.createElement('div');
                dragHint.className = 'drag-hint';
                dragHint.textContent = '可拖动调整顺序';
                imagesList.appendChild(dragHint);
            }

            // 创建图片网格
            const imageGrid = document.createElement('div');
            imageGrid.className = 'images-grid';
            imagesList.appendChild(imageGrid);

            currentImages.forEach((imageData, index) => {
                const imageContainer = document.createElement('div');
                imageContainer.className = 'image-item';
                imageContainer.setAttribute('data-index', index);
                imageContainer.draggable = true;
                
                // 添加拖拽事件
                imageContainer.addEventListener('dragstart', handleDragStart);
                imageContainer.addEventListener('dragover', handleImageDragOver);
                imageContainer.addEventListener('drop', handleImageDrop);
                imageContainer.addEventListener('dragend', handleDragEnd);

                const imgWrapper = document.createElement('div');
                imgWrapper.className = 'image-preview-wrapper';

                const img = document.createElement('img');
                img.src = imageData.url;
                img.className = 'preview-thumbnail';
                img.alt = `图片 ${index + 1}`;
                
                const infoOverlay = document.createElement('div');
                infoOverlay.className = 'image-info-overlay';
                
                // 显示图片类型图标
                const typeIcon = document.createElement('span');
                typeIcon.className = 'type-icon';
                typeIcon.textContent = imageData.type === 'file' ? '📁' : 
                                      (imageData.type === 'url' ? '🔗' : '🔄');
                
                // 创建序号徽章
                const badge = document.createElement('div');
                badge.className = 'image-number';
                badge.textContent = index + 1;
                
                const removeBtn = document.createElement('button');
                removeBtn.type = 'button';
                removeBtn.className = 'remove-image-btn';
                removeBtn.innerHTML = '✕';
                removeBtn.onclick = (e) => {
                    e.stopPropagation();
                    removeImage(index);
                };
                
                // 图片简短信息
                let shortInfo = '';
                if (imageData.type === 'file') {
                    const fileName = imageData.info.split(':')[1].trim().split(' ')[0];
                    shortInfo = fileName.length > 10 ? fileName.substring(0, 7) + '...' : fileName;
                } else if (imageData.type === 'url') {
                    shortInfo = '链接图片';
                } else {
                    shortInfo = '重用图片';
                }
                
                const infoText = document.createElement('div');
                infoText.className = 'image-short-info';
                infoText.title = imageData.info;
                infoText.textContent = shortInfo;

                imgWrapper.appendChild(img);
                imgWrapper.appendChild(badge);
                imgWrapper.appendChild(removeBtn);
                
                infoOverlay.appendChild(typeIcon);
                infoOverlay.appendChild(infoText);
                
                imageContainer.appendChild(imgWrapper);
                imageContainer.appendChild(infoOverlay);
                imageGrid.appendChild(imageContainer);
            });
        }
        
        // 拖拽排序功能
        function handleDragStart(e) {
            e.dataTransfer.setData('text/plain', e.target.getAttribute('data-index'));
            e.target.classList.add('dragging');
        }
        
        function handleImageDragOver(e) {
            e.preventDefault();
            e.dataTransfer.dropEffect = 'move';
        }
        
        function handleImageDrop(e) {
            e.preventDefault();
            const sourceIndex = parseInt(e.dataTransfer.getData('text/plain'));
            const targetIndex = parseInt(e.currentTarget.getAttribute('data-index'));
            
            if (sourceIndex !== targetIndex && sourceIndex >= 0 && targetIndex >= 0) {
                // 使用简单有效的数组重排序方法
                const tempImage = currentImages[sourceIndex];
                const tempFile = uploadedFiles[sourceIndex] || null;
                
                // 从数组中移除源元素
                currentImages.splice(sourceIndex, 1);
                if (tempFile) {
                    uploadedFiles.splice(sourceIndex, 1);
                }
                
                // 计算正确的插入位置
                let insertIndex = targetIndex;
                if (sourceIndex < targetIndex) {
                    // 从前面拖到后面，由于已经删除了前面的元素，索引需要减1
                    insertIndex = targetIndex - 1;
                }
                // 如果从后面拖到前面，insertIndex就是targetIndex
                
                // 在新位置插入元素
                currentImages.splice(insertIndex, 0, tempImage);
                if (tempFile) {
                    uploadedFiles.splice(insertIndex, 0, tempFile);
                }
                
                updateImagesPreview();
                showImageRearrangeSuccess();
            }
        }
        
        function handleDragEnd(e) {
            document.querySelectorAll('.image-item').forEach(item => {
                item.classList.remove('dragging');
            });
        }
        
        // 显示图片排序成功提示
        function showImageRearrangeSuccess() {
            const successMsg = document.createElement('div');
            successMsg.className = 'floating-success';
            successMsg.textContent = '✅ 图片顺序已更新';
            document.body.appendChild(successMsg);
            
            setTimeout(() => {
                document.body.removeChild(successMsg);
            }, 2000);
        }

        function createImagesPreviewElements() {
            const imagePreview = document.getElementById('imagePreview');
            imagePreview.innerHTML = `
                <div id="imagesList" class="images-list"></div>
                <button type="button" id="clearAllBtn" class="clear-image" style="display: none;">🗑️ 清除所有</button>
            `;
            
            document.getElementById('clearAllBtn').onclick = clearAllImages;
        }

        function removeImage(index) {
            currentImages.splice(index, 1);
            uploadedFiles.splice(index, 1);
            updateImagesPreview();
        }

        function clearAllImages() {
            currentImages = [];
            uploadedFiles = [];
            document.getElementById('imageUrl').value = '';
            document.getElementById('fileInput').value = '';
            updateImagesPreview();
        }

        async function handleUrlPreview() {
            const url = document.getElementById('imageUrl').value.trim();
            if (!url) {
                showError('请输入图片 URL');
                return;
            }

            try {
                // 验证 URL 是否为有效图片
                const img = new Image();
                img.onload = function () {
                    const imageData = {
                        url: url,
                        file: null,
                        info: `URL: ${url.substring(0, 50)}${url.length > 50 ? '...' : ''}`,
                        type: 'url'
                    };
                    currentImages.push(imageData);
                    updateImagesPreview();
                    
                    // 清空输入框
                    document.getElementById('imageUrl').value = '';
                };
                img.onerror = function () {
                    showError('无法加载图片，请检查 URL 是否正确');
                };
                img.src = url;
            } catch (error) {
                showError('URL 格式不正确');
            }
        }



        function clearImage() {
            clearAllImages();
        }

        function handleDragOver(e) {
            e.preventDefault();
            // 只在拖拽文件时显示拖拽效果
            if (e.dataTransfer.types.includes('Files')) {
                document.body.classList.add('dragover-body');
                const imageInputSection = document.getElementById('imageInputSection');
                if (imageInputSection) {
                    imageInputSection.classList.add('dragover');
                }
            }
        }

        function handleDragLeave(e) {
            e.preventDefault();
            // 只有当鼠标离开整个页面时才移除拖拽效果
            if (e.clientX === 0 && e.clientY === 0) {
                document.body.classList.remove('dragover-body');
                const imageInputSection = document.getElementById('imageInputSection');
                if (imageInputSection) {
                    imageInputSection.classList.remove('dragover');
                }
            }
        }

        function handleDrop(e) {
            e.preventDefault();
            // 移除拖拽效果样式
            document.body.classList.remove('dragover-body');
            const imageInputSection = document.getElementById('imageInputSection');
            if (imageInputSection) {
                imageInputSection.classList.remove('dragover');
            }

            // 处理文件拖拽
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                for (let i = 0; i < files.length; i++) {
                    const file = files[i];
                    if (file.type.startsWith('image/')) {
                        addImageFile(file);
                    }
                }
                return;
            }

            // 处理图片数据拖拽（如从网页拖拽图片）
            const items = e.dataTransfer.items;
            if (items) {
                for (let i = 0; i < items.length; i++) {
                    const item = items[i];

                    // 处理图片文件
                    if (item.kind === 'file' && item.type.startsWith('image/')) {
                        const file = item.getAsFile();
                        if (file) {
                            addImageFile(file);
                            return;
                        }
                    }

                    // 处理图片 URL
                    if (item.kind === 'string' && item.type === 'text/uri-list') {
                        item.getAsString((url) => {
                            if (url && (url.startsWith('http') || url.startsWith('data:image'))) {
                                document.getElementById('imageUrl').value = url;
                                handleUrlPreview();
                            }
                        });
                        return;
                    }
                }
            }
        }

        // 剪贴板粘贴处理
        async function handlePaste(e) {
            const items = e.clipboardData?.items;
            if (!items) return;

            for (let i = 0; i < items.length; i++) {
                const item = items[i];

                // 处理图片文件
                if (item.kind === 'file' && item.type.startsWith('image/')) {
                    e.preventDefault();
                    const file = item.getAsFile();
                    if (file) {
                        await addImageFile(file);
                        showPasteSuccess();
                    }
                    return;
                }

                // 处理图片 URL
                if (item.kind === 'string' && item.type === 'text/plain') {
                    item.getAsString((text) => {
                        if (text && (text.startsWith('http') && (text.includes('.jpg') || text.includes('.png') || text.includes('.gif') || text.includes('.webp')))) {
                            e.preventDefault();
                            document.getElementById('imageUrl').value = text;
                            handleUrlPreview();
                            showPasteSuccess();
                        }
                    });
                    return;
                }
            }
        }

        // 键盘快捷键处理
        function handleKeyDown(e) {
            // Ctrl+V 或 Cmd+V 粘贴提示
            if ((e.ctrlKey || e.metaKey) && e.key === 'v') {
                const imageInputSection = document.getElementById('imageInputSection');
                imageInputSection.classList.add('paste-ready');
                setTimeout(() => {
                    imageInputSection.classList.remove('paste-ready');
                }, 2000);
            }
        }

        // 手动粘贴按钮
        async function pasteFromClipboard() {
            try {
                const clipboardItems = await navigator.clipboard.read();

                for (const clipboardItem of clipboardItems) {
                    for (const type of clipboardItem.types) {
                        if (type.startsWith('image/')) {
                            const blob = await clipboardItem.getType(type);
                            const file = new File([blob], `pasted-image.${type.split('/')[1]}`, { type });
                            await addImageFile(file);
                            showPasteSuccess();
                            return;
                        }
                    }
                }

                // 如果没有图片，尝试读取文本（可能是图片URL）
                try {
                    const text = await navigator.clipboard.readText();
                    if (text && (text.startsWith('http') && (text.includes('.jpg') || text.includes('.png') || text.includes('.gif') || text.includes('.webp')))) {
                        document.getElementById('imageUrl').value = text;
                        handleUrlPreview();
                        showPasteSuccess();
                        return;
                    }
                } catch (textError) {
                    console.log('无法读取剪贴板文本');
                }

                showError('剪贴板中没有找到图片或图片URL');
            } catch (error) {
                console.error('读取剪贴板失败:', error);
                showError('无法访问剪贴板，请确保已授予权限或使用 Ctrl+V 粘贴');
            }
        }

        // 显示粘贴成功提示
        function showPasteSuccess() {
            const successMsg = document.createElement('div');
            successMsg.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: #059669;
                color: white;
                padding: 12px 20px;
                border-radius: 8px;
                z-index: 1000;
                font-size: 14px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            `;
            successMsg.textContent = '✅ 图片已从剪贴板粘贴成功';
            document.body.appendChild(successMsg);

            setTimeout(() => {
                if (document.body.contains(successMsg)) {
                    document.body.removeChild(successMsg);
                }
            }, 3000);
        }

        async function handleFormSubmit(e) {
            e.preventDefault();

            const formData = new FormData(e.target);
            const prompt = formData.get('prompt');

            if (!prompt || prompt.trim() === '') {
                showError('请输入编辑提示词');
                return;
            }

            hideError();
            hideResult();

            const data = {
                images: currentImages,
                prompt: prompt.trim()
            };

            // 显示处理加载状态
            showLoading('正在处理中，请稍候...');

            try {
                const response = await editImage(data);
                showResult(response.editedImageUrls);
            } catch (error) {
                showError(error.message);
            } finally {
                hideLoading();
            }
        }

        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }





        async function editImage(data) {
            const { images, prompt } = data;
            return await editImageWithGemini(images, prompt);
        }





        async function editImageWithGemini(images, prompt) {
            const url = `${BASE_URL}/chat/completions`;
            const headers = {
                Authorization: `Bearer ${API_KEY}`,
                "Content-Type": "application/json",
            };

            // 构建content数组，先添加文本提示
            const content = [
                {
                    type: "text",
                    text: prompt,
                }
            ];

            // 如果有图片，为每张图片添加image_url对象
            if (images && images.length > 0) {
                images.forEach(imageData => {
                    content.push({
                        type: "image_url",
                        image_url: {
                            url: imageData.url,
                        },
                    });
                });
            }

            const requestBody = {
                model: "gemini-2.5-flash-image-preview",
                stream: false,
                messages: [
                    {
                        role: "user",
                        content: content,
                    },
                ],
            };

            try {
                console.log("正在发送 Gemini 请求...");
                const response = await fetch(url, {
                    method: "POST",
                    headers,
                    body: JSON.stringify(requestBody),
                });

                if (!response.ok) {
                    let errorMsg = `Gemini API 请求失败 (${response.status}): ${response.statusText}`;
                    try {
                        const errorData = await response.json();
                        if (errorData.error && errorData.error.message) {
                            errorMsg = `Gemini API 请求失败 (${response.status}): ${errorData.error.message}`;
                        } else if (errorData.message) {
                            errorMsg = `Gemini API 请求失败 (${response.status}): ${errorData.message}`;
                        } else {
                            errorMsg = `Gemini API 请求失败 (${response.status}): ${JSON.stringify(errorData)}`;
                        }
                    } catch (jsonError) {
                        const text = await response.text();
                        errorMsg = `Gemini API 请求失败 (${response.status}): ${text}`;
                    }
                    throw new Error(errorMsg);
                }

                const result = await response.json();
                console.log("✅ Gemini API 响应成功。");

                // 检查响应中是否包含图像数据
                if (!result.choices || result.choices.length === 0) {
                    throw new Error("Gemini API 没有返回图片数据。");
                }

                // 从响应中提取图像URL - 处理第一个choice
                const choice = result.choices[0];
                if (!choice.message || choice.message.content === undefined) {
                    throw new Error("Gemini API 返回的数据格式不符合预期。");
                }

                // 处理返回的 Markdown 格式字符串
                const contentStr = choice.message.content;
                console.log("Gemini 返回内容:", contentStr);

                // 提取图片URL的正则表达式 - 支持HTTP URL和base64数据
                const imageUrlRegex = /!\[.*?\]\(((?:https?:\/\/[^\s)]+|data:image\/[^;]+;base64,[A-Za-z0-9+\/=]+))\)|(?:https?:\/\/[^\s\[\]()]+\.(?:png|jpg|jpeg|gif|webp)|data:image\/[^;]+;base64,[A-Za-z0-9+\/=]+)/gi;
                let match;
                const imageUrls = [];

                // 逐个提取所有匹配的URL
                while ((match = imageUrlRegex.exec(contentStr)) !== null) {
                    console.log("匹配到的内容:", match);
                    if (match[1]) {
                        // markdown格式中的URL
                        imageUrls.push(match[1]);
                        console.log("提取markdown中的URL:", match[1]);
                    } else if (match[0]) {
                        // 直接的URL
                        imageUrls.push(match[0]);
                        console.log("提取直接URL:", match[0]);
                    }
                }

                if (imageUrls.length === 0) {
                    throw new Error("在 Gemini API 响应中未找到可用的图片链接");
                }

                console.log("提取到的图片URL:", imageUrls);

                return { editedImageUrls: imageUrls };
            } catch (error) {
                console.error(`❌ Gemini 图片编辑失败: ${error instanceof Error ? error.message : String(error)}`);
                throw error;
            }
        }

        function showLoading(message = '正在处理中，请稍候...') {
            const loadingDiv = document.getElementById('loading');
            const loadingText = loadingDiv.querySelector('p');
            loadingText.textContent = message;
            loadingDiv.style.display = 'block';
            document.getElementById('submitBtn').disabled = true;
        }

        function hideLoading() {
            document.getElementById('loading').style.display = 'none';
            document.getElementById('submitBtn').disabled = false;
        }

        function showError(message) {
            const errorDiv = document.getElementById('error');
            errorDiv.textContent = message;
            errorDiv.style.display = 'block';
        }

        function hideError() {
            document.getElementById('error').style.display = 'none';
        }

        function showResult(imageUrls) {
            const resultDiv = document.getElementById('result');
            const imageGrid = document.getElementById('imageGrid');
            const clearResultBtn = document.getElementById('clearResultBtn');

            // 清空之前的结果
            imageGrid.innerHTML = '';
            
            // 显示结果区域和清除按钮
            resultDiv.style.display = 'block';
            clearResultBtn.style.display = 'inline-block';

            // 添加新的图片
            imageUrls.forEach((url, index) => {
                // 创建图片容器
                const imageContainer = document.createElement('div');
                imageContainer.className = 'result-image-container';

                // 创建图片元素
                const img = document.createElement('img');
                img.src = url;
                img.className = 'result-image';
                img.alt = '编辑后的图片';

                // 创建按钮容器
                const buttonContainer = document.createElement('div');
                buttonContainer.className = 'result-image-buttons';

                // 创建 Reuse 按钮
                const reuseBtn = document.createElement('button');
                reuseBtn.className = 'reuse-btn';
                reuseBtn.textContent = '🔄 重新编辑';
                reuseBtn.title = '使用此图片作为新的原图';
                reuseBtn.onclick = () => reuseImage(url);

                // 创建下载按钮
                const downloadBtn = document.createElement('button');
                downloadBtn.className = 'download-btn';
                downloadBtn.textContent = '💾 下载';
                downloadBtn.title = '下载此图片';
                downloadBtn.onclick = () => downloadImage(url, `edited_image_${index + 1}.png`);

                // 组装元素
                buttonContainer.appendChild(reuseBtn);
                buttonContainer.appendChild(downloadBtn);
                imageContainer.appendChild(img);
                imageContainer.appendChild(buttonContainer);
                imageGrid.appendChild(imageContainer);
            });

            resultDiv.style.display = 'block';
        }

        function hideResult() {
            document.getElementById('result').style.display = 'none';
        }

        function clearResult() {
            const imageGrid = document.getElementById('imageGrid');
            const clearResultBtn = document.getElementById('clearResultBtn');
            
            // 清空结果图片
            imageGrid.innerHTML = '';
            
            // 隐藏结果区域和清除按钮
            hideResult();
            clearResultBtn.style.display = 'none';
            
            // 显示成功提示
            const successMsg = document.createElement('div');
            successMsg.className = 'floating-success';
            successMsg.textContent = '✅ 编辑结果已清除';
            document.body.appendChild(successMsg);
            
            setTimeout(() => {
                document.body.removeChild(successMsg);
            }, 2000);
        }

        function reuseImage(imageUrl) {
            // 清空当前所有图片
            currentImages = [];
            uploadedFiles = [];
            
            // 添加选择的图片
            const imageData = {
                url: imageUrl,
                file: null,
                info: `重用图片: ${imageUrl.substring(0, 50)}${imageUrl.length > 50 ? '...' : ''}`,
                type: 'reuse'
            };
            currentImages.push(imageData);
            updateImagesPreview();

            // 清空提示词，让用户输入新的编辑指令
            document.getElementById('prompt').value = '';

            // 滚动到顶部
            window.scrollTo({ top: 0, behavior: 'smooth' });

            // 显示成功提示
            const successMsg = document.createElement('div');
            successMsg.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: #059669;
                color: white;
                padding: 12px 20px;
                border-radius: 8px;
                z-index: 1000;
                font-size: 14px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            `;
            successMsg.textContent = '✅ 图片已添加，请输入新的编辑提示词';
            document.body.appendChild(successMsg);

            // 3秒后移除提示
            setTimeout(() => {
                document.body.removeChild(successMsg);
            }, 3000);
        }

        async function downloadImage(imageUrl, filename) {
            try {
                // 显示下载中状态
                const downloadBtn = document.querySelector('.download-btn');
                if (downloadBtn) {
                    downloadBtn.textContent = '⏳ 下载中...';
                    downloadBtn.disabled = true;
                }
                
                if (imageUrl.startsWith('data:image/')) {
                    // 处理base64格式的图片
                    const [header, base64Data] = imageUrl.split(',');
                    const mimeMatch = header.match(/data:([^;]+)/);
                    const mimeType = mimeMatch ? mimeMatch[1] : 'image/png';
                    
                    // 解码base64数据
                    const binaryString = atob(base64Data);
                    const bytes = new Uint8Array(binaryString.length);
                    for (let i = 0; i < binaryString.length; i++) {
                        bytes[i] = binaryString.charCodeAt(i);
                    }
                    
                    // 创建blob
                    const blob = new Blob([bytes], { type: mimeType });
                    triggerDownload(blob, filename || `generated-image.${mimeType.split('/')[1]}`);
                } else {
                    // 处理HTTP/HTTPS URL
                    try {
                        // 尝试通过fetch获取图片
                        const response = await fetch(imageUrl);
                        if (!response.ok) throw new Error('Network response was not ok');
                        
                        const blob = await response.blob();
                        const mimeType = blob.type || 'image/png';
                        triggerDownload(blob, filename || `downloaded-image.${mimeType.split('/')[1]}`);
                    } catch (fetchError) {
                        console.error('通过fetch下载图片失败:', fetchError);
                        // 如果fetch失败，回退到打开新标签页
                        window.open(imageUrl, '_blank');
                    }
                }
            } catch (error) {
                console.error('下载图片失败:', error);
                // 如果处理失败，尝试在新标签页打开
                window.open(imageUrl, '_blank');
            } finally {
                // 恢复按钮状态
                const downloadBtn = document.querySelector('.download-btn');
                if (downloadBtn) {
                    downloadBtn.textContent = '💾 下载';
                    downloadBtn.disabled = false;
                }
            }
        }
        
        // 辅助函数：触发文件下载
        function triggerDownload(blob, filename) {
            const downloadUrl = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = downloadUrl;
            link.download = filename;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            
            // 清理URL对象
            setTimeout(() => URL.revokeObjectURL(downloadUrl), 100);
        }


    </script>
</body>

</html>